<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <areas :area-type="areaType" :areas="treeAreas" v-on:handleNodeClick="onHandleNodeClick"/>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-card>
          <div class="filter-container">
            <el-input v-model="listQuery.device_number" class="filter-item" clearable
                      placeholder="终端编号" style="margin-left: 20px;width: 140px"></el-input>
            <el-select v-model="listQuery.unit" class="filter-item" clearable placeholder="单元号"
                       style="margin-left: 20px;width: 110px">
              <el-option
                v-for="item in units"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            <el-input v-model="listQuery.floor" class="filter-item" clearable placeholder="楼层"
                      style="margin-left: 10px;width: 120px" type="number"></el-input>
            <el-input v-model="listQuery.room_number" class="filter-item" clearable placeholder="门牌号"
                      style="margin-left: 10px;width: 120px" type="number"></el-input>
            <el-date-picker v-model="listQuery.date_range" :picker-options="pickerOptions" class="filter-item"
                            clearable
                            end-placeholder="结束日期"
                            range-separator="至"
                            start-placeholder="开始日期"
                            style="margin-left:20px"
                            type="daterange"
                            unlink-panels
                            value-format="yyyy-MM-dd">
            </el-date-picker>
            <el-button v-if="checkPermission('查询记录')" class="filter-item" icon="el-icon-search" style="margin-left:40px"
                       type="primary" @click="getMeterList">
              查询
            </el-button>
          </div>
          <div class="filter-container">
<!--            <el-button v-if="checkPermission('导出记录')" :loading="exportLoading" class="filter-item"-->
<!--                       icon="el-icon-download" style="margin-left: 10px" type="primary" @click="exportMeter">-->
<!--              导出-->
<!--            </el-button>-->
          </div>
          <div class="app-container">
            <el-table
              :key="tableKey"
              ref="equipTable"
              v-loading="listLoading"
              :cell-style="{padding:0+'px'}"
              :data="list"
              :row-style="{height:40+'px'}"
              border
              fit
              height="600"
              highlight-current-row
              stripe
              style="width: 100%;"
            >
              <el-table-column
                v-if="isLatest"
                type="selection"
                width="40">
              </el-table-column>
              <el-table-column :fixed="this.columns.length > 7" align="center" label="终端编号" width="150">
                <template slot-scope="{row}">
                  <span>{{ row.terminal_number }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="水司编号" width="160">
                <template slot-scope="{row}">
                  <span>{{ row.refer_number || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="所属用户" width="200">
                <template slot-scope="{row}">
                  <span>{{ row.unit + '/' + row.floor + '层/' + row.room_number }}</span>
                </template>
              </el-table-column>

              <el-table-column v-if="checkColumns('settlement_daily_volume')" align="center" label="结算水量(m³)"
                               width="130">
                <template slot-scope="{row}">
                  <span>{{ row.meter_id ? row.settlement_daily_volume : '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column v-if="checkColumns('left_volume')" align="center" label="剩余水量(m³)"
                               width="130">
                <template slot-scope="{row}">
                  <span>{{ row.meter_id ? row.left_volume : '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column v-if="checkColumns('left_amount')" align="center" label="剩余金额" width="200">
                <template slot-scope="{row}">
                  <span>{{ row.meter_id ? row.left_amount : '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column v-if="checkColumns('period_volume')" align="center" label="周期用水量" width="200">
                <template slot-scope="{row}">
                  <span>{{ row.meter_id ? row.period_volume : '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column v-if="checkColumns('unit_price')" align="center" label="当前单价" width="200">
                <template slot-scope="{row}">
                  <span>{{ row.meter_id ? row.unit_price : '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column v-if="checkColumns('warning_volume')" align="center" label="预警水量" width="200">
                <template slot-scope="{row}">
                  <span>{{ row.meter_id ? row.warning_volume : '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column v-if="checkColumns('valve_close_volume')" align="center" label="关阀水量" width="200">
                <template slot-scope="{row}">
                  <span>{{ row.meter_id ? row.valve_close_volume : '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column :fixed="this.columns.length > 7 ?'right':false" align="center" class-name="small-padding fixed-width" label="操作"
                               width="120">
                <template slot-scope="{row,$index}">
                  <el-button v-if="checkPermission('24小时水量')" circle icon="el-icon-s-data" title="24小时水量" type="primary"
                             @click="handleDLog(row.day_meter)">
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total>0" :limit.sync="listQuery.pageSize" :page.sync="listQuery.page" :total="total"
                        @pagination="getMeterList"/>
            <el-dialog :visible.sync="dialogLogVisible" title="24小时数据">
                {{ datMeter }}
            </el-dialog>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import areas from '@/components/area/AreaTree'
import Pagination from '@/components/Pagination'
import {exportMeter, getList} from "@/api/meter";
import {getAreaTree} from "@/api/area";
import {checkPermission} from "@/utils/permission";
import {mapGetters} from 'vuex';
import jsUtils from 'jutils-src'


export default {
  name: 'PrePaid',
  components: {areas, Pagination,},
  data() {
    return {
      tableKey: 0,
      dialogCommandVisible: false,
      dialogVolumeVisible: false,
      btnLoading: false,
      dialogLogVisible: false,
      dialogChartVisible: false,
      exportLoading: false,
      listLoading: true,
      activeValue: 1,
      inactiveValue: 0,
      list: [],
      datMeter: [],
      listType: 'latest',
      total: 0,
      areaType: 2,
      chartData: {},
      listQuery: {
        area_code: '',
        floor: '',
        room_number: '',
        offline_days: 2,
        unit: '',
        electrica_fault_status: -1,
        sensor_warning_status: -1,
        meter_battery_status: -1,
        leakage_alarm_status: -1,
        reverse_warning_status: -1,
        positive_volume_min: '',
        positive_volume_max: '',
        reverse_volume_min: '',
        reverse_volume_max: '',
        atc_status: -1,
        valve_status: -1,
        reset_status: -1,
        device_code: '',
        date_range: [''],
        page: 1,
        pageSize: 20
      },
      units: ['一单元', '二单元', '三单元', '四单元', '五单元', '六单元', '七单元', '八单元', '九单元', '十单元'],
      workModels: [{name: '线断', value: 1}, {name: '检定模式', value: 2}, {name: '洗阀模式', value: 3}],
      treeAreas: [],
      exportData: {
        list: [],
        headers: []
      },
      rules: {
        plain_text : [ { required: true, message: '请输入人工报文', trigger: 'blur' }]
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    }
  },
  created() {
    this.getMeterList()
    this.getAreaTree()
  },
  computed: {
    isLatest() {
      return this.listType === 'latest'
    },
    ...mapGetters([
      'columns'
    ])
  },
  methods: {
    checkPermission,
    checkColumns(columns) {
      return this.columns.includes(columns)
    },
    exportMeter() {
      this.exportLoading = true
      const query = Object.assign({}, this.listQuery)
      query.electrica_fault_status =query.electrica_fault_status || -1
      query.sensor_warning_status = query.sensor_warning_status || -1
      query.meter_battery_status = query.meter_battery_status || -1
      query.leakage_alarm_status = query.leakage_alarm_status || -1
      query.valve_status = query.valve_status || -1
      query.positive_volume_max = query.positive_volume_max || 0
      query.positive_volume_min = query.positive_volume_min || 0
      query.reverse_volume_max = query.reverse_volume_max || 0
      query.reverse_volume_min = query.reverse_volume_min || 0
      query.offline_days = parseInt(query.offline_days) || 0
      exportMeter(query).then(res => {
        if (res.code == 20000) {
          this.exportData.list = res.data.list
          this.exportData.headers = res.data.headers
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = this.exportData.headers
            const data = this.exportData.list
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '抄表数据',
              autoWidth: true,
              bookType: 'xlsx'
            })
            this.exportLoading = false
          })
        }
      })
    },
    getAreaTree(type) {
      getAreaTree({type: 2}).then(response => {
        this.treeAreas = response.data
      })
    },
    handleDLog(raw) {
      this.datMeter = raw
      this.dialogLogVisible = true
    },
    onHandleNodeClick: function (data) {
      if (this.listQuery.area_code != data.code) {
        this.listQuery.area_code = data.code
        this.getMeterList()
      }
    },
    getMeterList() {
      this.listLoading = true
      const query = Object.assign({}, this.listQuery)
      query.electrica_fault_status = this.listQuery.electrica_fault_status || -1
      query.sensor_warning_status = this.listQuery.sensor_warning_status || -1
      query.meter_battery_status = this.listQuery.meter_battery_status || -1
      query.leakage_alarm_status = this.listQuery.leakage_alarm_status || -1
      query.positive_volume_max = this.listQuery.positive_volume_max || 0
      query.positive_volume_min = this.listQuery.positive_volume_min || 0
      query.reverse_volume_max = this.listQuery.reverse_volume_max || 0
      query.reverse_volume_min = this.listQuery.reverse_volume_min || 0
      getList(query).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listType = response.data.type
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    resetQueryParams() {
      this.listQuery = {
        area_code: '',
        floor: '',
        room_number: '',
        unit: '',
        electrica_fault_status: -1,
        sensor_warning_status: -1,
        meter_battery_status: -1,
        leakage_alarm_status: -1,
        reverse_warning_status: -1,
        positive_volume_min: '',
        positive_volume_max: '',
        reverse_volume_min: '',
        reverse_volume_max: '',
        atc_status: -1,
        reset_status: -1,
        device_code: '',
        date_range: [''],
        page: 1,
        pageSize: 20
      }
    },
    formatDate(dateStr) {
      const d = new Date(dateStr)
      if (d.getMilliseconds() == 0) {
        return '-'
      }
      return jsUtils.formatDate(d, 'YYYY-MM-DD HH:ii:ss')
    },
    formatStatus(status) {
      switch (status) {
        case 0:
          return 'danger'
        case 1:
          return 'success'
        case 2:
          return 'warning'
      }
    },
  }
}
</script>
